﻿using SuperX.Common.Log;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Threading.Tasks;

namespace SuperX.SuperSocket.Socket.Transfer.Server.UpLoad.Command
{
    public class DoData : CommandBase<TransferSession, BinaryRequestInfo>
    {
        public override void ExecuteCommand(TransferSession session, BinaryRequestInfo requestInfo)
        {
            try
            {
                if (session.FileTransferEngine != null)
                {
                    lock (session.FileTransferEngine.lockobj)
                    {
                        session.FileTransferEngine.m_fileStream.Write(requestInfo.Body, 0, requestInfo.Body.Length);
                        session.FileTransferEngine.UpLoadInfo.TransferedLength += requestInfo.Body.Length;
                        session.FileTransferEngine.OnTransferStep(
                            session.FileTransferEngine.UpLoadInfo.TransferLength,
                            session.FileTransferEngine.UpLoadInfo.TransferedLength,
                            requestInfo.Body.Length);
                        if (session.FileTransferEngine.UpLoadInfo.TransferLength <= session.FileTransferEngine.UpLoadInfo.TransferedLength)
                        {
                            Task.Factory.StartNew(() =>
                            {
                                session.FileTransferEngine.m_EndEvent.WaitOne(5000);
                                session.FileTransferEngine.DoUploadEnd();
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
            }
        }
    }
}